﻿# -*- coding: UTF-8 -*-

import os
import re
import win32com
import time
from win32com.client import Dispatch
from email.header import Header 

#发件人设置
mail_host=""  #设置服务器
mail_user=""    #用户名
mail_pass=""   #口令
eml=''
qqfile=''
fromfile=''

def initData():
    eml=getfilepath("mail.eml")
    qqfile=getfilepath("qq.txt")
    fromfile=getfilepath("from.txt")
    f = open(fromfile)
    mail_host=f.readline()
    mail_user=f.readline()
    mail_pass=f.readline()
    f.close()
    return eml,qqfile,fromfile,mail_host,mail_user,mail_pass
    

class SendEML:
    def __init__(self, uid, pwd, server='smtp.sina.com', port=25):
        self.oMsg= win32com.client.Dispatch('CDO.Message')        
        iConfg= self.oMsg.Configuration.Fields
        iConfg['http://schemas.microsoft.com/cdo/configuration/sendusing'].Value=2
        iConfg['http://schemas.microsoft.com/cdo/configuration/smtpserverport'].Value=port
        iConfg['http://schemas.microsoft.com/cdo/configuration/smtpserver'].Value=server
        iConfg['http://schemas.microsoft.com/cdo/configuration/sendusername'].Value=uid
        iConfg['http://schemas.microsoft.com/cdo/configuration/sendpassword'].Value=pwd
        iConfg['http://schemas.microsoft.com/cdo/configuration/smtpauthenticate'].Value=1
        iConfg['http://schemas.microsoft.com/cdo/configuration/smtpusessl'].Value=True
        iConfg.Update()

    def send(self,fromm,to,eml):
        stm = win32com.client.Dispatch('ADODB.Stream')
        stm.Open(Mode= 2, Options=1)
        stm.Type = 1
        stm.LoadFromFile(eml)
        self.oMsg.DataSource.OpenObject(stm, "_stream")
        stm.Close()
        
        self.oMsg.From=fromm
        self.oMsg.To=to      
        #print (self.oMsg.Textbody+self.oMsg.HTMLbody)
        #print (self.oMsg.Attachments.Count)
        self.oMsg.Send()
        return True

def getqqlist():
    qqf= open(qqfile,'r')
    qqstream=qqf.read()
    qqlist = qqstream.split(",")
    qqf.close()
    return qqlist

def getfilepath(relativepath):
    APATH = os.path.abspath('.')
    file_path = os.path.join(APATH,'set',relativepath)
    return file_path


if __name__ == "__main__":
    eml,qqfile,fromfile,mail_host,mail_user,mail_pass=initData()
    #print (eml+qqfile+fromfile)
    #print (mail_host+mail_user+mail_pass)
    mailto_list=getqqlist()
    for mailto_item in mailto_list:
        if not mailto_item.strip():
            continue
        email = SendEML(mail_user,mail_pass)
        if email.send(mail_user,mailto_item,eml):  
            print (mailto_item+" ----- send success")
            time.sleep(60)
        else:  
            print (mailto_item+" send error")